<template>
  <div>
    <div class="contract-list-page">
      <!-- 导航栏 -->
      <CommonHeader
        :header-obj="{ title: $t('合同查询'), rightText: '', leftText: '' }"
        show-left-arrow
        @left-click="handleBack"
      />

      <!-- 搜索栏 -->
      <van-search
        v-model="searchKeyword"
        :placeholder="$t('请输入客户名称、编码、订单编号等搜索')"
        @search="handleSearch"
        class="search-bar"
      />

      <!-- 时间 -->
      <div class="chose-time">
        <van-popover
          v-model="showPopover"
          trigger="click"
          placement="left"
          :actions="actions"
          @select="onSelect"
        >
          <template #reference>
            <span>{{ timeText }} <van-icon name="arrow" /></span>
          </template>
        </van-popover>
      </div>

      <!-- 合同列表 -->
      <pull-refresh-list
        ref="pullRefreshList"
        :fetch-data="fetchContractList"
        :initial-params="params"
        :page-size="10"
      >
        <div slot-scope="{ item, index }" class="review-container">
          <div @click="handleContractClick(item)">
            <div class="header">
              <div class="title">{{ item.contractNumber }}</div>
              <div :class="getStatusClass(item.freezeState)">
                {{ freezeStateMap[item.freezeState] }}
              </div>
            </div>
            <div class="review-content">
              <div class="info-row">
                <div class="label">{{ $t('评审单号') }}</div>
                <div class="value">{{ item.judgeNumber }}</div>
              </div>
              <div class="info-row">
                <div class="label">{{ $t('客户') }}</div>
                <div class="value">{{ item.signTarget }}</div>
              </div>
              <div class="info-row">
                <div class="label">{{ $t('签约主体') }}</div>
                <div class="value">{{ item.signSubject }}</div>
              </div>
              <div class="info-row">
                <div class="label">{{ $t('有效期限') }}</div>
                <div class="value">{{ item.startEndTime }}</div>
              </div>
            </div>
          </div>
          <div class="action-buttons">
            <button
              class="copy-btn"
              @click="handleCopy(item)"
              v-permission="['HTCX-COPY']"
            >
              {{ $t('复制') }}
            </button>
            <button
              class="reject-btn"
              v-if="[0].includes(item.freezeState)"
              @click="handleFreeze(item, 1)"
              v-permission="['HTCX-DJ']"
            >
              {{ $t('冻结') }}
            </button>
            <button
              class="approve-btn"
              v-if="[1].includes(item.freezeState)"
              v-permission="['HTCX-QXDJ']"
              @click="handleFreeze(item, 2)"
            >
              {{ $t('取消冻结') }}
            </button>
            <button
              class="delete-btn"
              @click="handleInvalid(item, 3)"
              v-if="item.showEffectiveFlag == 1"
              v-permission="['HTCX-CANCEL']"
            >
              {{ $t('作废') }}
            </button>
          </div>
        </div>
      </pull-refresh-list>
    </div>

    <!-- 日期选择器 -->
    <van-popup v-model="showDatePickerPopup" position="bottom">
      <van-calendar
        v-model="showDatePickerPopup"
        type="range"
        :min-date="minDate"
        @confirm="onDateConfirm"
        @cancel="showDatePickerPopup = false"
      />
    </van-popup>
    <!-- min -->
    <CustomActionSheet
      :modelValue="show"
      :title="actionText"
      :confirm-text="$t('确认')"
      :cancel-text="$t('取消')"
      @confirm="handleConfirm"
      @cancel="handleCancel"
      :showFooter="true"
    >
      <template #content>
        <div class="reject-content" v-if="actionText != $t('确认作废？')">
          <p>{{ $t('合同编号：') }}{{ itemObj.contractNumber }}</p>
          <p>{{ $t('版本号：') }}{{ itemObj.contractVersion }}</p>
          <van-field
            v-model="remark"
            :label="$t('备注')"
            type="textarea"
            :placeholder="$t('请输入备注')"
            label-align="top"
            :auto-height="true"
          />
        </div>
        <div class="invalid-content" v-else>
          {{ $t('作废合同后') }}<span>{{ $t('合同失效且不可恢复') }}</span
          >{{ $t('，确认要作废合同吗？') }}
        </div>
      </template>
    </CustomActionSheet>
  </div>
</template>
<script>
import {
  getContractQueryList,
  freezeContract,
  invalidContract,
} from '@/api/contract'
import CustomActionSheet from '@/components/CustomActionSheet.vue'
import CommonHeader from '@/components/CommonHeader.vue'
import PullRefreshList from '@/components/PullRefreshList.vue'
import { Toast, Dialog } from 'vant'
import dayjs from 'dayjs'

export default {
  name: 'CreateList',
  components: {
    CustomActionSheet,
    CommonHeader,
    PullRefreshList,
  },
  data() {
    return {
      // 状态定义
      minDate: new Date(1990, 0, 1),
      maxDate: new Date(2025, 11, 31),
      // 响应式数据
      remark: '',
      showDatePickerPopup: false,
      timeText: this.$t('全部时间'),
      show: false,
      actionText: '',
      itemObj: '',
      rejectReason: '',
      tempShow: false,
      tempKeyword: '', // 模板关键词
      tempChecked: null, // 模板选中
      tempList: [],
      currentPage: 1,
      tempPages: {
        nowPage: 1,
        pageSize: 10,
        total: 0,
      },
      // 状态筛选映射
      freezeStateMap: {
        0: this.$t('未冻结'),
        1: this.$t('已冻结'),
      },
      activeTab: '-1',
      searchKeyword: '',
      showPopover: false,
      actions: [
        { text: this.$t('全部时间') },
        { text: this.$t('近一个月') },
        { text: this.$t('近三个月') },
        { text: this.$t('近半年') },
        { text: this.$t('自定义时间') },
      ],
      // 列表参数
      params: {
        formState: null,
        keyword: '',
        createdTimeS: null,
        createdTimeE: null,
        nowPage: 1,
        pageSize: 10,
      },
    }
  },
  created() {},
  watch: {
    searchKeyword(val) {
      this.params.keyword = val
      this.$refs.pullRefreshList.onRefresh()
    },
  },
  methods: {
    fetchContractList() {
      return new Promise((resolve, reject) => {
        getContractQueryList(this.params).then((res) => {
          resolve(res)
        })
      })
    },

    handleBack() {
      console.log('[ handleBack ]-173', 111)
      this.$router.go(-1)
    },

    handleSearch() {
      this.$refs.pullRefreshList.onRefresh()
    },

    handleTabChange(v) {
      // 创建新对象以触发参数变化检测
      this.params = {
        ...this.params,
        formState: v === '-1' ? null : v,
      }
      this.$refs.pullRefreshList.onRefresh()
    },

    // 合同点击
    handleContractClick(row) {
      this.$router.push({
        path: '/contract/detail',
        query: {
          formId: row.formId,
          definitionId: row.definitionId,
          definitionCode: row.definitionCode,
          judgeNumber: row.judgeNumber,
          contractSource: 0,
          readonly: true,
          formQuery: true,
          oaFlag: 1,
        },
      })
      //  formId: row.formId,
      //           definitionId: row.definitionId,
      //           definitionCode: row.definitionCode,
      //           judgeNumber: row.judgeNumber,
      //           contractSource: 0,
      //           readonly: true,
      //           formQuery: true,
    },

    // 时间选择
    onSelect({ text }) {
      console.log('[ text ]-205', text)
      switch (text) {
        case this.$t('全部时间'):
          this.params.createdTimeS = null
          this.params.createdTimeE = null
          this.timeText = this.$t('全部时间')
          this.$refs.pullRefreshList.onRefresh()
          break
        case this.$t('近一个月'):
          this.params.createdTimeS = dayjs()
            .subtract(1, 'month')
            .format('YYYY-MM-DD')
          this.params.createdTimeE = dayjs().format('YYYY-MM-DD')
          this.timeText = this.$t('近一个月')
          this.$refs.pullRefreshList.onRefresh()
          break
        case this.$t('近三个月'):
          this.params.createdTimeS = dayjs()
            .subtract(3, 'month')
            .format('YYYY-MM-DD')
          this.params.createdTimeE = dayjs().format('YYYY-MM-DD')
          this.timeText = this.$t('近三个月')
          this.$refs.pullRefreshList.onRefresh()
          break
        case this.$t('近半年'):
          this.params.createdTimeS = dayjs()
            .subtract(6, 'month')
            .format('YYYY-MM-DD')
          this.params.createdTimeE = dayjs().format('YYYY-MM-DD')
          this.timeText = this.$t('近半年')
          this.$refs.pullRefreshList.onRefresh()
          break
        default:
          this.showDatePickerPopup = true
          break
      }
    },

    // 日期选择器确认
    onDateConfirm(value) {
      if (value && value.length === 2) {
        const startDate = dayjs(value[0]).format('YYYY-MM-DD')
        const endDate = dayjs(value[1]).format('YYYY-MM-DD')
        this.params.createdTimeS = startDate
        this.params.createdTimeE = endDate
        this.timeText = this.$t('{startDate} 至 {endDate}', {
          startDate: startDate,
          endDate: endDate,
        })

        this.showDatePickerPopup = false
      }
      this.fetchContractList(true)
    },
    handleCopy(row) {
      this.$router.push({
        path: '/contract/contractCopy',
        query: {
          formId: row.formId,
          definitionId: row.definitionId,
          definitionCode: row.definitionCode,
          copy: true,
          pageFrom: 'add',
        },
      })
    },
    // 作废
    handleInvalid(item) {
      this.show = true
      this.itemObj = item
      this.actionText = this.$t('确认作废？')
    },
    handleFreeze(item, type) {
      this.itemObj = item
      this.actionText =
        type == 1 ? this.$t('确认冻结合同？') : this.$t('确认取消冻结合同？')
      this.show = true
    },
    // 自定义面板事件处理
    async handleConfirm() {
      if (this.actionText == this.$t('确认作废？')) {
        const res = await invalidContract({
          formId: this.itemObj.formId,
        })
        if (res.data.resultCode == '0000') {
          Toast(this.$t('操作成功'))
          this.show = false
          this.remark = ''
        }
      } else {
        const res = await freezeContract({
          formId: this.itemObj.formId,
          freezeType: this.actionText == this.$t('确认冻结合同？') ? 1 : 2,
          remark: this.remark,
        })

        if (res.data.resultCode == '0000') {
          Toast(this.$t('操作成功'))
          this.show = false
          this.remark = ''
        }
      }
    },

    handleCancel() {
      this.show = false
    },

    handleConfirmTemp() {
      this.$router.push({
        path: '/contract/createContract',
        query: {
          templateId: this.tempChecked.templateId,
        },
      })
    },

    handleCancelTemp() {
      this.tempShow = false
    },

    getStatusClass(status) {
      switch (status) {
        case 1:
          return 'status-completed'
        case 2:
          return 'status-reject'
        case 3:
          return 'status-expired'
        case 0:
          return 'status-processing'
        default:
          return 'status'
      }
    },
  },
}
</script>
<style lang="scss" scoped>
.reject-content {
  padding: 0 16px 100px 16px;
  font-size: 14px;
}
.re-red {
  font-style: normal;
  color: red;
  font-size: 14px;
}
.chose-time {
  color: #666666;
  line-height: 21px;
  text-align: right;
  font-style: normal;
  display: flex;
  justify-content: flex-end;
  margin-top: 15px;
  span {
    height: 21px;
    display: flex;
    font-weight: 400;
    font-size: 15px;
    align-items: center;
  }
}

.contract-list-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.search-bar {
  padding: 10px;
  background-color: #fff;
}

.filter-tabs {
  background-color: #fff;
}

.contract-list {
  background-color: #f5f5f5;
  padding: 10px;
}
.review-container {
  margin: 0 10px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  background: #fff;
  margin-top: 10px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 14px;
}

.title {
  font-weight: 500;
  font-size: 16px;
  color: #333333;
  line-height: 23px;
  text-align: left;
  font-style: normal;
}

.status {
  color: #fe890f;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 14px;
}

.review-content {
  padding: 0 16px;
}

.info-row {
  display: flex;
  margin-bottom: 12px;
}

.label {
  width: 100px;
  color: #666;
  font-size: 14px;
}

.value {
  flex: 1;
  font-size: 14px;
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  padding: 0 16px;
  margin-bottom: 10px;
}

button {
  padding: 8px 16px;
  margin-left: 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 13px;
  background: transparent;
  display: flex;
  align-items: center;
}

.reject-btn {
  height: 26px;
  border-radius: 15px;
  border: 1px solid #fec39e;
  color: #ff8512;
}

.approve-btn {
  height: 26px;
  border-radius: 15px;
  border: 1px solid #a5abff;
  color: #5762f4;
}

.delete-btn {
  height: 26px;
  border-radius: 15px;
  border: 1px solid #eb5353;
  color: #ec1111;
}
.copy-btn {
  height: 26px;
  border-radius: 15px;
  border: 1px solid #5762f4;
  color: #5762f4;
}

button:hover {
  opacity: 0.8;
}
.status-tag {
  padding: 2px 8px;
  border-radius: 12px;
}
.status-processing {
  color: #fe890f;
  font-size: 16px;
}

.status-completed {
  color: #23c176;
  font-size: 16px;
}

.status-reject {
  color: #f83232;
  font-size: 16px;
}
.invalid-content {
  height: 180px;
  font-size: 14px;
  text-align: center;
  line-height: 100px;
  span {
    color: #ff8919;
  }
}
</style>
